#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Kumikoda on 2017/6/17

from flask import render_template, Response
from flask import request
from flask import jsonify
from flask import session
from flask import redirect
from flask import url_for

import os

from modules import users, confs, cmdb, inquire, statistics, ssh


from flask import Flask
app = Flask(__name__)
app.secret_key = '2EsDrsG3qeLWsrXHtLmRRj4P'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/user/login', methods=['POST', 'GET'])
def login():
    result = {}
    if request.method == 'POST':
        user_info = request.form.to_dict()
        if 'phone' in user_info and 'passwd' in user_info:
            if user_info['phone'] and user_info['passwd']:
                u = users.Users(**user_info)
                result = u.login()
                if result['code'] == 0: # 正确跳转首页
                    session['phone'] = user_info['phone']
                    return redirect(url_for('index'))
            else:
                result = {
                    'code': 4,
                    'message': confs._code.get(4, '请填写正确完整信息')
                }
        else:
            result = {
                'code': 4,
                'message': confs._code.get(4, '请填写正确完整信息')
            }
    return render_template('login.html', result=result)

@app.route('/user/logout')
def logout():
    del session['phone']
    return redirect(url_for('index'))

@app.route('/user/reg', methods=['POST', 'GET'])
def reg():
    result = {}
    if request.method == 'POST':
        reg_info = request.form.to_dict()
        u = users.Users(reg_info=reg_info)
        result = u.reg()
        if result.get('code', 54) == 0:
            return redirect(url_for('index'))
    return render_template('register.html', result=result)

## 平台首页
@app.route('/admin')
def admin():
    result = {}
    return render_template('admin.html',result=result)

## 修改用户信息
@app.route('/user/edit', methods=['POST', 'GET'])
def user_edit():
    result = {}
    code = message = None

    u =users.Users()
    if request.method == 'POST':
        phone = request.form['phone']
        username = request.form['username']
        mail = request.form['mail']
        en_mail = request.form['en_mail']
        center = request.form['center']
        section_ = request.form['section_']
        edit_result = u.edit_user(
            phone=phone,
            username=username,
            mail=mail,
            en_mail=en_mail,
            center=center,
            section_=section_
        )
        code, message = edit_result['code'], edit_result['message']
    phone = session['phone']
    result = u.fetch_user(phone=phone)
    return render_template('user_edit.html', result=result, code=code, message=message)



#修改cmdb
# @app.route('/cmdb/edit/<id>', methods=['POST'])
# def edit_cmdb(id):
#     print id
#     return Response('111111')

#显示cmdb
@app.route('/cmdb/<action>', methods=['POST', 'GET'])
@app.route('/cmdb/<action>/<asset>', methods=['POST', 'GET'])
def view_cmdb(action, asset=None):
    actions = ['add','del','edit','list']
    assets = ['room','cabinet','host']
    if request.method == 'GET':
        if action == 'add':
            return render_template('cmdbadd.html')
        elif action == 'edit':
            return render_template('cmdbedit.html')
        else:
            c = cmdb.CMDB()
            if asset == 'room':  # 查
                result = c.list_room()
                return render_template('cmdbroomlist.html', result=result)
            elif asset == 'cabinet':
                result = c.list_cabinet()
                return render_template('cmdbcabinetlist.html', result=result)
            else:
                result = c.list_host()
                # print c.list_host()['message']
                # print c.list_host()['data']
                return render_template('cmdbhostlist.html', result=result)
    elif request.method == 'POST':
        c = cmdb.CMDB()
        info = request.form.to_dict()
        if action == 'add':  # 增加机柜
            if assets == 'room':
                result = c.add_room(**info)
            elif assets == 'cabinet':  # 添加机柜
                result = c.add_cabinet(**info)
            elif assets == 'host':
                result = c.add_host(**info)
        elif action == 'del':
            if assets == 'room':
                result = c.del_room(**info)
                return redirect('/cmdb/list/room')
            elif assets == 'cabinet':
                result = c.del_cabinet(**info)
                return redirect('/cmdb/list/cabinet')
            else:  # 删除主机
                result = c.del_host(**info)
                return redirect('/cmdb/list/host')
        elif action == 'edit':
            if asset == 'room':
                result = c.edit_room(**info)
            elif asset == 'cabinet':
                result = c.edit_cabinet(**info)
            elif asset == 'host':  # 修改主机
                # result = c.add_host(**info)
                hostid = request.form.to_dict()['id']
                host_info = c.hostInfobyID(hostid)['data']
                return render_template('cmdbedit.html', host_info=host_info)
            elif asset == 'save':
                host_info = request.form.to_dict()
                result = c.modify_host(host_info['id'],host_info['assets_number'],host_info['IDC_type'],host_info['room_info'],
                              host_info['cabinet_info'],host_info['serial_number'],host_info['model_number'],host_info['wan_ip'],
                              host_info['ip'],host_info['remote_ip'],host_info['status'],host_info['assets_user'],
                              host_info['business_type'],host_info['business_name'],host_info['detailed_action'],
                              host_info['upline_time'],host_info['downline_time'],host_info['osystem'],
                              host_info['source'],host_info['deadline'],host_info['contract_number'],
                              host_info['price'],host_info['monthly_fee'],host_info['up_time'],
                              host_info['down_time'],host_info['usage_days'],host_info['monthbilling'],
                              host_info['comment'],host_info['cpu'],host_info['mem'],host_info['disk'],
                              )
                return redirect('/cmdb/list/host')

            else: # 修改主机
                # 在这里把值 cmdbhostlist.html 提交过来的值  获取下来
                # 做CMDB修改
                pass
                result = c.modify_host(**info)
                # print result
                return redirect('/cmdb/edit/host')
        else:
            result = {'code': 204, 'message': '请提交正确的URL'}
        return jsonify(result)
    else:
        return jsonify({'code': 203, 'message': '服务器不支持get/post以外的请求'})


## 分类查询主机
@app.route('/cmdb/select/host', methods=['GET', 'POST'])
def select_host(action, asset):
    if request.method == 'POST':
        c = inquire.Inquire()
        info = request.form.to_dict()
        nonull_info = {}
        if action == 'select':
            if asset == 'host':
                return c.inquire(**info)
            else:
                result = c.inquire(**info)
                return redirect('/cmdb/select/host')
        for e in info:
            if info[e] != '':
                nonull_info[e] = info[e]
        print nonull_info
        sql = ''
        for (k, v) in nonull_info.iteritems():
            v0 = v.strip()
            #   sql0 += ' a.%s = \'%s\' and ' % (k, v0)
            sql += ' a.%s like \'%s%%\' and ' % (k, v0)
        sql = sql.rstrip(" and ")
        print sql
        result = c.inquire(sql)
        return render_template('cmdbhostlist.html', result=result)

##  服务器统计
@app.route('/cmdb/count/servers', methods=['POST', 'GET'])
def count_server():
    s = statistics.Statistics()
    info = request.form.to_dict()
    nonull_info  ={}
    for e in info:
        if info[e] != '':
            nonull_info[e] = info[e]
    print (nonull_info)
    uptime_start = nonull_info.get('upline_start') ## 查询时间资产信息的条件
    uptime_end = nonull_info.get('upline_end')  ## 查询时间资产信息的条件
    print uptime_end

    sql0 = '' ## 临时变量
    sql = 'upline_time >= \'%s\' and upline_time <= \'%s\' ' % (uptime_start, uptime_end)
    if len(nonull_info) == 2:
        sql =sql
    else:
        del (nonull_info['upline_start'])
        del (nonull_info['upline_end'])
        for (k, v) in nonull_info.iteritems():
            v0 = v.strip()
            sql0 = 'and status = "使用" group by %s HAVING sum(monthbilling) > 0 order by servers_used desc' % k
        sql += sql0 ## SQL语句的拼接
    print sql
    result = s.count2_servers(sql)
    return render_template('statement_servers.html',result=result)


## 服务器使用总数条件查询--统计列表
@app.route('/cmdb/total_number/use', methods=['POST', 'GET'])
def total_number():
    s = statistics.Statistics()
    info  =request.form.to_dict()
    print info
    nonull_info = {}
    for e in info:
        if info[e] != '':
            nonull_info[e] = info[e]
    print nonull_info
    sql =''
    for (k, v) in nonull_info.iteritems():
        sql = ' status = \'使用\' group by %s HAVING sum(m.monthbilling) > 0 order by servers_used desc' % v
    result = s.operation_servers(sql)
    return render_template('operation_servers.html', result=result)


## 业务类型月度计费
@app.route('/cmdb/operation/billing',methods=['POST','GET'])
def count_billing():
    s = statistics.Statistics()
    info = request.form.to_dict()
    nonull_info = {}
    for e in info:
        if info[e] != '':
            nonull_info[e] = info[e]
    print nonull_info
    #uptime0 = nonull_info.get('upline_time0')
    #uptime0 = uptime0.strip()
    sql = ' upline_time >= \'%s\' and upline_time <= \'%s\' and status = \'使用\' group by  %s order by %s  desc'  % (
        nonull_info['upline_start'], nonull_info['upline_end'], nonull_info['groupby'], nonull_info['orderby']
    )
    result = s.operation_servers(sql)
    return  render_template('operation_billing.html',result=result)

@app.route('/statement/<action>/',methods=['POST','GET'])
@app.route('/statement/<action>/<asset>/',methods=['POST','GET'])
def view_statistics(action='business', asset='billing'):
    actions = ['business','operation']
    assets = ['servers','billing']
    if request.method == 'GET':
        if action == 'operation':
            s = statistics.Statistics()
            if asset == 'billing':
                result = s.count_list_billing()
                return render_template('operation_billing.html', result=result)
            else:
                result = s.count_list_servers()
                return render_template('operation_servers.html',result=result)
        else:
            s = statistics.Statistics()
            if asset == 'billing':
                result = s.count_billing()
                return render_template('statement_billing.html',result=result)
            else:
                result = s.count_servers()
                return render_template('statement_servers.html',result=result)
    elif request.method == 'POST':
        s = statistics.Statistics()
        info = request.form.to_dict()
        if action == 'operation':
            if asset == 'billing':
                result = s.operation_billing(**info)
                return redirect('/statement/operation/billing')
            elif asset == 'servers':
                result = s.operation_servers(**info)
                return redirect('/statement/operation/servers')
        elif action == 'business':
            if asset == 'billing':
                result = s.count_billing(**info)
                return redirect('/statement/business/billing')
            else:
                result = s.count_servers(**info)
                return redirect('/statement/business/servers')
        else:
            result = {'code':204,'message':'请提交正确的URL'}
        return jsonify(result)
    else:
        return jsonify({'code': 203, 'message': '服务器不支持get/post以外的请求'})


## 远程批量命令以及批量上传
@app.route('/tools/run', methods=['POST', 'GET'])
def run():
    result = {}
    s = ssh.SSH()
    hosts = s.view_hosts()
    if request.method == 'POST':
        runs = request.form.to_dict()
        if 'host' and 'command' in runs:
            if runs['host']:
                host_info  = s.get_hosts(runs['host'])
                if host_info.get('code', 1) != 0:
                    result = host_info
                else:
                    host_info = host_info['host']
                    result = s.execute(command=runs['command'], host_info=host_info)
            else:
                result = {'code': 411, 'message' : '参数不能为空'}
        else:
            result = {'code': 410, 'message' : '提供参数不全'}
    return render_template('run.html', result=result, hosts=hosts)

@app.route('/tools/mult_run', methods=['POST', 'GET'])
def mult_run():
    result = {}
    if request.method == 'POST':
        mult_runs = request.form.to_dict()
        if mult_runs.get('command',''):
            s = ssh.SSH()
            result = s.mult_execute(mult_runs['command'])
        else:
            result = {'code' : 402, 'message' : '参数不能为空'}
    return render_template('mult_run.html', result=result)

@app.route('/tools/mult_upload', methods=['POST', 'GET'])
def mult_upload():
    result = {}
    if request.method == 'POST':
        file = request.files['excelfile']
        filename = file.filename
        path = os.path.join(confs.upath, filename)
        file.save(path)
        s = ssh.SSH()
        rpath = confs.rupath + filename
        result = s.mult_upload(lpath=path, rpath=rpath)
    return render_template('mult_upload.html', result=result)





if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9001, debug=True)

